package com.dream.mqpushserver.handler;

import com.dream.mqpushserver.netty.Request;
import com.dream.mqpushserver.netty.RequestCode;
import com.dream.mqpushserver.netty.RequestCommand;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author song_
 * @Date 2020/3/24
 * @desc
 **/
public class ServerHandler extends SimpleChannelInboundHandler<Request> {

    private static AtomicInteger integer = new AtomicInteger(0);

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channel activite ...");
        ctx.writeAndFlush(RequestCommand.buildRequestCommand(RequestCode.RESPONSE, "this is connect response ".getBytes()));
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Request command) throws Exception {
        System.out.println(command);
        Request request = new Request();
        request.setType((byte) 2);
        String content = "this is server response ";
        request.setLength(content.length());
        request.setContent(content);
        ctx.channel().writeAndFlush(request);
        System.out.println("serve has responsed ...." + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        RequestCommand requestCommand = RequestCommand.buildRequestCommand(RequestCode.RESPONSE, "this is response ...".getBytes());
        ctx.pipeline().channel().writeAndFlush(requestCommand);
        ctx.writeAndFlush(requestCommand);
    }
}